<?php

namespace app\common\service\finance;

use app\common\service\finance\FinanceScene\FinanceSceneBase;
use app\model\Agent;
use app\model\AgentBalanceLog;
use think\Exception;
use think\facade\Db;

class FinanceManager
{

    const TYPE_DEC = 'dec';
    const TYPE_INC = 'inc';

    const BALANCE_PROFIT = 1;//佣金余额
    const BALANCE_BALANCE = 2;//预充的余额


    /**
     * @var FinanceSceneBase $obj
     */
    public static function handle($obj)
    {

        if (empty($obj->type()) || empty($obj->moneyChange())) {
            throw new Exception('缺少致命参数Finance');
        }

        $objres = $obj->handle();
        if (!$objres) return false;


        Db::transaction(function () use ($obj) {


            $agent = Agent::query()->where('id', $obj->agentId())->lock()->find();
            if (empty($agent)) {
                throw new Exception('代理不存在 error: FinanceManager');
            }


            //先扣款
            $agentMoneyRes = Agent::query()
                ->where('id', $obj->agentId())
                ->when($obj->balanceType() == self::BALANCE_PROFIT, function ($query) use ($obj) {
                    $query->{$obj->moneyChange()}('profit_balance', abs($obj->amount()));
                    $query->{$obj->moneyChange()}('total_profit', abs($obj->amount()));
                })
                ->when($obj->balanceType() == self::BALANCE_BALANCE, function ($query) use ($obj) {
                    $query->{$obj->moneyChange()}('balance', abs($obj->amount()));

                    if ($obj->moneyChange() == self::TYPE_DEC){
                        $query ->where('balance', '>=', $obj->amount());
                    }

                })
                ->update([
                    'balance_last_updated_at' => date('Y-m-d H:i:s'),
                ]);

            if (!$agentMoneyRes){
                return false;
            }


            //加日志
            $agentNew = Agent::query()->where('id', $obj->agentId())->find();
            (new AgentBalanceLog([
                'agent_id' => $obj->agentId(),
                'type' => $obj->type(),
                'amount' => $obj->moneyChange() == self::TYPE_DEC ? -abs($obj->amount()) :''.abs($obj->amount()),
                'old_balance' => $obj->balanceType() == self::BALANCE_PROFIT ? $agent->profit_balance : $agent->balance,
                'new_balance' => $obj->balanceType() == self::BALANCE_PROFIT ? $agentNew->profit_balance : $agentNew->balance,
                'remark' => $obj->remark(),
                'quote_id' => $obj->quoteId(),
                'trade_no' => $obj->tradeNo(),
            ]))->save();

        });


        return true;



    }
}